//
//  UploadHeadTool.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/11/14.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  上传头像

import UIKit

class UploadHeadTool: UIView,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIAlertViewDelegate {
    static let shared = UploadHeadTool()
    
    let imagePicker = UIImagePickerController()
    
    var alertController = UIAlertController()
    /**
     ## 图片来源
     */
    
    //外部闭包变量
    var comfun:((_ _data:Data,_ _dic : NSDictionary)->Void)?
    
    func choosePic(_com:@escaping (_ _data:Data,_ _dic : NSDictionary)->Void) -> Void {
        
        //将函数闭包对应的地址指向外界对应的地址
        comfun = _com
        
        //弹出选择图片来源控制器
        alertController = UIAlertController.init(title: "提示", message: "请选择图片来源", preferredStyle: UIAlertControllerStyle.actionSheet)
        
        //取消事件
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in
            self.alertController.removeFromParentViewController()
        }
        
        //本地相册图库
        let localPhotoLibrary = UIAlertAction(title: "本地", style: .default) { (_) in
            self.uploadHeadImg()
            self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            self.alertController.dismiss(animated: true, completion: nil)
        }
        
        //照片来源相机
        let chooseFromCamera = UIAlertAction(title: "拍照", style: .default) { (_) in
            print("拍照")
            
            
            //判断相机是否可以用
            if self.isCameraAvailable(){
                
                self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
                self.uploadHeadImg()
            } else {
                MBManager.showBriefAlert("相机不可用")
                return
                
            }

        }
        
        //添加选择项
        alertController.addAction(cancelAction)
        alertController.addAction(localPhotoLibrary)
        alertController.addAction(chooseFromCamera)
    
        
        //弹出actionsheet
        nav?.present(alertController, animated: true, completion: nil)
    }
    
}



// MARK:- 图片上传
extension UploadHeadTool {
    //图片选择器
    func uploadHeadImg() {
        
        //移除弹窗
        self.alertController.removeFromParentViewController()
        
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        //图片源:相册
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            
            imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            
        }
        

        //图片源:相机
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            
            imagePicker.sourceType = UIImagePickerControllerSourceType.camera
            
        }

        
       //弹出选择相册的控制器
        UIApplication.shared.keyWindow?.rootViewController?.present(imagePicker, animated: true, completion: nil)

    }
    
    
    /**
     ## 上传图片
     */
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            
            print("ddddd")
            //改变图片大小
            let small = scaleToSize(img: image, size: CGSize(width: 140, height: 140))
            
            
            let compresImage = UIImageJPEGRepresentation(small, 0.1) as Data!
            
            guard let token = localSave.object(forKey: userToken) as? String else {
                return
            }
            
            let url = "\(upphotoURL)\("?token=")\(token)"
            
            picker.dismiss(animated: true, completion: nil)
            
            _refresh = 1
            
            postWithImageWithData(imgData: compresImage!, path: url, success: { (response) in
                
                //判读返回值是否为空
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String
                
                
                
                
                if alertmsg == "成功" {

                    _headImg = compresImage!
                    
                    print("原始hedimg数据",_headImg.count)
                    
                    //将值传给闭包
                    
                    //本地标识为0 不刷新表格头

                    self.comfun!(_headImg,dic)
                    
                    //存入本地，方便启动后显示无须网络请求
                    localSave.removeObject(forKey: headImgCache)
                    
                    localSave.set(compresImage, forKey: headImgCache)
                    localSave.synchronize()
                    
                    //提示语
//                    MBManager.showBriefAlert(uploadHeadSucces)
                    CustomAlertView.shared.alertWithTitle(strTitle: uploadHeadImgSuccess)

                }
                
                print(dic)
                
                
            }, failure: { (error) in
                print(error.localizedDescription)
                CustomAlertView.shared.alertWithTitle(strTitle: netWrong)
            })
            
        }
}
}

// MARK:- 判断相机是否可用
extension UploadHeadTool {
    /**
     ## 判断相机是否可用
     - BOOL    相机是否可用
     */
    func isCameraAvailable() -> Bool{
        return UIImagePickerController.isCameraDeviceAvailable(.rear) && UIImagePickerController.isSourceTypeAvailable(.camera)
    }

}

